package cn.stylefeng.guns.modular.web.service.impl;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.modular.web.entity.PlUser;
import cn.stylefeng.guns.modular.web.entity.UserGoldLog;
import cn.stylefeng.guns.modular.web.mapper.PlUserMapper;
import cn.stylefeng.guns.modular.web.service.IPlUserService;
import cn.stylefeng.guns.modular.web.service.IUserGoldLogService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Map;

/**
 * 描述：用户表 service业务层
 * 作者：chenhuiyan
 * 时间：2020-04-13
 */
@Service
@Transactional(readOnly = true)
public class PlUserServiceImpl extends ServiceImpl<PlUserMapper, PlUser> implements IPlUserService {

    @Autowired
    private IUserGoldLogService userGoldLogService;

    /**
     * 查询列表
     * @param params
     * @return
     */
    public Page<Map<String, Object>> list(Map<String, Object> params) {
        Page page = LayuiPageFactory.defaultPage();
        return this.baseMapper.list(page, params);
    }

    /**
     * 修改用户金币
     * @param userId 用户编号
     * @param changeType 变动类型（0增加，1减少）
     * @param changeGold 变动数量
     * @param reson 修改原因
     */
    @Transactional
    public void updateGold(String userId, Integer changeType, Integer changeGold, String reson){

        //生成修改记录
        UserGoldLog userGoldLog = new UserGoldLog();
        userGoldLog.preInsert();

        PlUser user = this.getById(userId);
        user.preUpdate();

        userGoldLog.setBeforeNum(user.getGold());

        if(changeType == 0){ //增加
            user.setGold(user.getGold().add(new BigDecimal(changeGold)));
        }else{ //减少
            user.setGold(user.getGold().subtract(new BigDecimal(changeGold)));
        }
        this.updateById(user);

        userGoldLog.setChangeType(changeType);
        userGoldLog.setChangeNum(new BigDecimal(changeGold));
        userGoldLog.setAfterNum(user.getGold());
        userGoldLog.setReson(reson);
        userGoldLog.setUserId(user.getId());
        userGoldLog.setType(2);
        userGoldLog.setMagicBoxId("111");
        userGoldLog.setSmPlanId("2222");

        userGoldLogService.save(userGoldLog);
    }

}
